<template>
  <div class="banner-manage-container">
    <el-card class="banner-manage-card">
      <!-- 工具栏 -->
      <div class="toolbar">
        <el-button type="primary" @click="handleAdd">添加 Banner</el-button>
      </div>

      <!-- Banner 列表 -->
      <el-table v-loading="loading" :data="bannerList" style="width: 100%" border>
        <el-table-column label="图片" width="200">
          <template #default="{ row }">
            <el-image :src="row.image" fit="cover" class="banner-image" />
          </template>
        </el-table-column>

        <el-table-column prop="title" label="标题" min-width="200" />

        <el-table-column prop="link" label="链接" min-width="200" show-overflow-tooltip>
          <template #default="{ row }">
            <el-link :href="row.link" target="_blank">{{ row.link || '无' }}</el-link>
          </template>
        </el-table-column>

        <el-table-column prop="sort_order" label="排序" width="100" align="center" />

        <el-table-column label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.is_active ? 'success' : 'info'">
              {{ row.is_active ? '已启用' : '已禁用' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button
              :type="row.is_active ? 'warning' : 'success'"
              link
              @click="handleToggleStatus(row)"
            >
              {{ row.is_active ? '禁用' : '启用' }}
            </el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑 Banner' : '添加 Banner'"
      width="500px"
    >
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="formData.title" />
        </el-form-item>

        <el-form-item label="图片" prop="image">
          <el-upload
            class="banner-uploader"
            action="#"
            :show-file-list="false"
            :auto-upload="false"
            :on-change="handleImageChange"
            :before-upload="beforeUpload"
          >
            <img v-if="formData.image" :src="formData.image" class="banner-preview" />
            <el-icon v-else class="banner-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">建议尺寸: 1920x600px</div>
        </el-form-item>

        <el-form-item label="链接" prop="link">
          <el-input v-model="formData.link" placeholder="选填" />
        </el-form-item>

        <el-form-item label="排序" prop="sort_order">
          <el-input-number v-model="formData.sort_order" :min="0" :max="99" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="saveLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import {
  getBannerList,
  createBanner,
  updateBanner,
  updateBannerStatus,
  deleteBanner,
} from '@/api/banner'
// import { uploadImage } from '@/api/upload'
import type { Banner } from '@/types/banner'
import { beforeUpload } from '@/utils/upload'
import type { FileItem, UploadFile } from '@/types/upload'
import { v4 as uuidv4 } from 'uuid'
import { uploadBanners } from '@/api/upload'

const loading = ref(false)
const saveLoading = ref(false)
const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref<FormInstance>()
const bannerList = ref<Banner[]>([])

const formData = ref({
  id: 0,
  title: '',
  image: '',
  link: '',
  sort_order: 0,
})

const rules: FormRules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  image: [{ required: true, message: '请上传图片', trigger: 'change' }],
  sort_order: [{ required: true, message: '请输入排序', trigger: 'blur' }],
}

// 获取列表
const fetchData = async () => {
  loading.value = true
  try {
    const { data } = await getBannerList()
    bannerList.value = data.data.items
  } catch (error) {
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 添加
const handleAdd = () => {
  isEdit.value = false
  formData.value = {
    id: 0,
    title: '',
    image: '',
    link: '',
    sort_order: 0,
  }
  dialogVisible.value = true
}

const singleFile = reactive<FileItem>({
  uid: '',
  name: '',
  status: 'ready',
})

// 编辑
const handleEdit = (row: Banner) => {
  isEdit.value = true
  formData.value = {
    id: row.id,
    title: row.title,
    image: row.image,
    link: row.link || '',
    sort_order: row.sort_order,
  }
  dialogVisible.value = true
}

// 切换状态
const handleToggleStatus = async (row: Banner) => {
  try {
    await updateBannerStatus(row.id)
    ElMessage.success('操作成功')
    fetchData()
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 删除
const handleDelete = async (row: Banner) => {
  try {
    await ElMessageBox.confirm('确定要删除该 Banner 吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    await deleteBanner(row.id)
    ElMessage.success('删除成功')
    fetchData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 图片上传相关
const handleImageChange = async (file: UploadFile) => {
  if (!beforeUpload(file.raw)) return
  const reader = new FileReader()
  reader.readAsDataURL(file.raw)
  reader.onload = async () => {
    Object.assign(singleFile, {
      uid: uuidv4(),
      name: file.name,
      url: reader.result as string,
      status: 'ready',
      raw: file.raw,
    })

    try {
      if (!singleFile.raw) {
        ElMessage.error('请选择文件')
        return
      }

      singleFile.status = 'uploading'
      singleFile.percentage = 0

      const response = await uploadBanners([singleFile.raw], (percentage) => {
        singleFile.percentage = percentage
      })

      singleFile.status = 'success'
      formData.value.image = response.data.data.files[0].url
      ElMessage.success('上传成功')
    } catch (error) {
      singleFile.status = 'error'
      ElMessage.error('上传失败')
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      saveLoading.value = true
      try {
        if (isEdit.value) {
          await updateBanner(formData.value.id, {
            title: formData.value.title,
            image: formData.value.image,
            link: formData.value.link,
            sort_order: formData.value.sort_order,
          })
          ElMessage.success('更新成功')
        } else {
          await createBanner({
            title: formData.value.title,
            image: formData.value.image,
            link: formData.value.link,
            sort_order: formData.value.sort_order,
          })
          ElMessage.success('添加成功')
        }
        dialogVisible.value = false
        fetchData()
      } catch (error) {
        ElMessage.error(isEdit.value ? '更新失败' : '添加失败')
      } finally {
        saveLoading.value = false
      }
    }
  })
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.banner-manage-container {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
  min-height: calc(100vh - 200px);
  box-sizing: border-box;
}

.banner-manage-card {
  margin-top: 0;
}

.toolbar {
  margin-bottom: 20px;
}

.banner-image {
  width: 160px;
  height: 50px;
  border-radius: 4px;
}

.banner-uploader {
  text-align: center;
}

.banner-preview {
  width: 360px;
  height: 112px;
  object-fit: cover;
  border-radius: 4px;
}

.banner-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 360px;
  height: 112px;
  line-height: 112px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
}

.banner-uploader:hover .banner-uploader-icon {
  border-color: #409eff;
  color: #409eff;
}

.upload-tip {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}
</style>
